﻿using Furion.DataEncryption;
using FurStudy.Core;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FurStudy.Application
{
    /// <summary>
    /// 安全鉴权
    /// </summary>
    public class SecurityAuthenticationService
    {
        private readonly User _user;
        private readonly HttpContextAccessor _httpContextAccessor;

        public SecurityAuthenticationService(User user, HttpContextAccessor httpContextAccessor)
        {
            _user = user;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 关于token
        /// 生成Token
        /// 当用户登录成功之后，返回accessToken字符串，之后通过JWTEncryption.GenerateRefreshToken()获取刷新Token，并通过响应报文头返回
        /// 用户登录成功之后把 accessToken 和 refreshToken 一起返回给客户端存储起来
        /// </summary>
        public void AboutToken()
        {
            // 生成Token
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>() 
            {
                { "UserId", _user.Id }, // 存储Id
                { "Account", _user.Account }, // 存储用户名
            });

            // 获取刷新Token
            var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 43200); // 第二个参数是刷新token的有效期（分钟），默认三十天

            // 设置响应报文头
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;
        }
    }
}
